#!/usr/bin/python3
# 文件名：client.py

# 导入 socket、sys 模块
import socket,time,os,re,pymysql,requests
def nmap_icmp():
    ip = ['113.215.3.64/26', '113.215.11.0/25', '113.215.11.128/25', '113.215.22.128/26','113.215.13.128/26']
    ipList=[]
    for x in ip:
        nmap=os.popen('/usr/bin/nmap -e eth1 -sP %s' % (x)).read()
        nmapRES=re.findall("\d+\.\d+\.\d+\.\d+",nmap)
        ipList.extend(nmapRES)
    return ipList





def updateDB(IP):#ip
    db=pymysql.connect("113.215.1.161","root","root","mydb",charset="utf8" )# 打开数据库连接
    cursor = db.cursor()# 使用cursor()方法获取操作游标
    #查询
    sqlFind='SELECT * FROM ten100 WHERE IP="%s"' % IP
    #更新
    sqlupdate='UPDATE ten100 SET new="no" WHERE IP="%s" ' % IP
    #插入
    sqlInsert='INSERT INTO ten100(IP,new) VALUES ("%s","yes")' % IP
    print(sqlFind)
    Find=cursor.execute(sqlFind)
    print("找到%s条记录" % Find)
    if Find==0:#如果库中无次记录
        try:
            cursor.execute(sqlInsert)  # 插入记录
            print(sqlInsert,"succese")
        except:
            print(sqlInsert,"failed")
            db.close()
            return 0
    else:
        try:
            cursor.execute(sqlupdate)#更新记录
            print(sqlupdate,"succese")
        except:
            print(sqlupdate, "failed")
            db.close()
            return 0
    db.close()




if __name__ == '__main__':
    # 创建 socket 对象

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 获取本地主机名
    host = "100.64.255.100"

    # 设置端口好
    port = 9999

    # 连接服务，指定主机和端口
    retry=0
    while True:
        try:
            s.connect((host, port))
            break
        except:
            print("30秒后重试")
            retry=retry+1
            time.sleep(30)
            if retry==2:
                print("连接超时")
                os.system('echo "100.64.255.100上的测试服务异常"  | /bin/mail -s "腾讯OC_100地址段无法访问" ganlian@watone.com.cn')
                os.system('echo "100.64.255.100上的测试服务异常"  | /bin/mail -s "腾讯OC_100地址段无法访问" songhp@watone.com.cn')
                break

    tenIP_HT=nmap_icmp()
    # 接收小于 1024 字节的数据
    tenIP_HW = requests.get("http://100.64.255.100/ten100HW.txt").text.split("\t")
    print("华通", tenIP_HT)
    print("杭网",tenIP_HW)
    diff=list(set(tenIP_HT).difference(set(tenIP_HW)))
    print("杭网无法访问",diff)
    db = pymysql.connect("113.215.1.161", "root", "root", "mydb", charset="utf8")  # 打开数据库连接
    cursor = db.cursor()
    cursor.execute("Truncate Table  ten100")
    db.close()
    for x in diff:
            updateDB(x)
    s.close()
    #except:

        #s.close()
        #print("异常退出")